<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
/********************
 *@param function:OplusCms 後臺頁面管理
 *@param datetime 2012-01-06
 *@param author solgh
 ********************/
class Pages extends Admins_Controller {
  
  private $data=array();
  private $page_id=0;
  public function __construct(){
    parent::__construct();
    $this->data['currentPage']='manages';
    $this->load->model('pages_mdl');
    //查詢語言
    $this->load->model('languages_mdl');
    $this->data['format_time']=$this->settings['default_time'];
    $this->data['languages']=$this->languages_mdl->get_core_languages(array('status'=>1));
	$this->data['lang'] =$this->lang->language;
    //$this->_get_menus();
  }

  public function index(){
    $this->get_list();
    $this->load->view('admins/pages_list_view',$this->data);
  }
  
  //獲取主要的menu歸屬
  private function _get_menus(){
     $data=array('language_id'=>2,'parent'=>0,'status'=>1);
     $query=$this->pages_mdl->get_pages($data);
     $result=array();
     foreach ($query->result_array() as $key => $list) {
       $result[$list['id']]=$list['title'];
     }
     $this->data['menus']=$result;
  }
  //獲取頁面列表
  private function get_list(){
    $page = $this->input->get('p',TRUE);
    $page = (!empty($page) && is_numeric($page)) ? intval($page) : 1;
    $limit = $this->settings['default_admin_limit']; //後臺列表默認個數.
    $offset = ($page - 1) * $limit;
    if($offset < 0){
      redirect('admins/pages');
    }
    $url_query=$_SERVER['QUERY_STRING'];
    // 保留查詢參數;
    $cookie = array(
        'name'   => 'url_query',
        'value'  => base64_encode($url_query),
        'expire' => '0',
        'path'   => '/',
    );
    $this->input->set_cookie($cookie);
    if(!empty($url_query)){
      $url_query=preg_replace('/&p=(\d+)/','',$url_query);
    }
    $this->data['title']=$this->input->get('title');
    $this->data['unique_url']=$this->input->get('unique_url');
    $this->data['parent']=$this->input->get('parent');
    
    $this->data['field']=$this->input->get('field');
    $this->data['sort']=$this->input->get('sort');
    $this->data['field']=!empty($this->data['field'])?$this->data['field']:'n.sort_order';
    $this->data['sort']=!empty($this->data['sort'])?$this->data['sort']:'asc';
        
    $data=array('language_id'=>$this->settings['default_language'],'limits'=>$limit,'offset'=>$offset);
    $data=!empty($this->data['title'])?array_merge($data,array('title'=>trim($this->data['title']))):$data;
    $data=!empty($this->data['unique_url'])?array_merge($data,array('unique_url'=>$this->data['unique_url'])):$data;
    $data=is_numeric($this->data['parent']) && $this->data['parent']>=0?array_merge($data,array('parent'=>trim($this->data['parent']))):$data;
    
    $data=!empty($this->data['field'])?array_merge($data,array('field'=>$this->data['field'])):$data;
    $data=!empty($this->data['sort'])?array_merge($data,array('sort'=>strtoupper($this->data['sort']))):$data;    
    
    $this->data['lists_count']=$this->pages_mdl->totle_pages($data);
    
    $pagination = '';
    if($this->data['lists_count'] > $limit)
    {
      $this->dpagination->currentPage($page);
      $this->dpagination->items($this->data['lists_count']);
      $this->dpagination->limit($limit);
      $this->dpagination->adjacents(5);
      $this->dpagination->target(site_url('admins/pages').'?'.$url_query);
      $this->dpagination->parameterName('p');
      $this->dpagination->nextLabel($this->data['lang']['orders_lable_19']);
      $this->dpagination->PrevLabel($this->data['lang']['orders_lable_18']);
      $pagination = $this->dpagination->getOutput();
    }
    $this->data['pagination'] = $pagination;
    $this->data['lists']=$this->pages_mdl->get_pages($data);
  }
  
  //新增頁面
  public function add(){
      $this->load->view('admins/pages_form_view',$this->data);
  }
  
  //修改頁面
  public function edit($edit_id=''){
    if(!empty($edit_id)){
       //基本信息
      $query=$this->pages_mdl->get_pages_by_id($edit_id);
      
      $this->data['edit_id']=$edit_id;
      foreach ($query as $key => $value) {
        $this->data[$key]=$value;
      }
      //資料 descriptions
      $results=$this->pages_mdl->get_descriptions($edit_id);

      foreach($results->result_array() as $rs){
        $this->data['descriptions'][$rs['language_id']]=$rs;
      } //end foreach;
       $this->load->view('admins/pages_form_view',$this->data);
    }else{
      show_error('對不起,參數出錯!');
      exit;
    }
  }
  
  //執行修改或添加
  public function modify(){
    $edit_id=$this->input->post('edit_id');
    $this->page_id=$edit_id;
    $this->_load_validation_rules();
    if ($this->form_validation->run() == FALSE)
    {
      $this->data['edit_id']=$edit_id;
      $this->data['error']=true;
      $this->load->view('admins/pages_form_view',$this->data);
    }else{
      $update_time=$this->input->post('update_time');
      $data['general']=array(
        'unique_url'=>$this->input->post('unique_url'),
        'sort_order'=>$this->input->post('sort_order'),
        'add_time'=>time(),
        'parent'=>$this->input->post('parent'),
        'update_time'=>!empty($update_time)?strtotime($update_time):time(),
        'status'=>$this->input->post('status'),
        'is_complete'=>$this->input->post('is_complete'),
        'is_new_window'=>$this->input->post('is_new_window'),
        'main_image'=>$this->input->post('main_image')
        );
      //多語言描述
      $data['descriptions']=$this->input->post('descriptions');
      ////添加或修改.
      if(!empty($edit_id) && $edit_id>0){
        $operator_title='修改基本頁面->'.$data['descriptions'][$this->settings['default_language']]['title'];
        $action='修改';
        $result=$this->pages_mdl->edit_pages($data,$edit_id);//修改.
      }else{
        $operator_title='新增基本頁面->'.$data['descriptions'][$this->settings['default_language']]['title'];
        $action='新增';
        $result=$this->pages_mdl->add_pages($data);//添加.
      }

      $this->operator_log($operator_title,$action,$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      $redirect=site_url('admins/pages').$this->settings['url_query'];//獲取列表篩選參數
      redirect($redirect);
      
    }
  }
  //數據格式驗證
  public function _load_validation_rules(){
      $this->form_validation->set_rules('unique_url','靜態網址','trim|required|alpha_dash|is_unique[clickrcms_page.unique_url.id.'.$this->page_id.']|max_length[20]');
      $this->form_validation->set_rules('sort_order','排序','required|trim|numeric|max_length[10]');
      $this->form_validation->set_rules('status','狀態','trim|required|numeric|max_length[1]');
      $this->form_validation->set_rules('is_complete','完整頁面','trim|numeric|max_length[1]');
      $this->form_validation->set_rules('is_new_window','新窗口','trim|numeric|max_length[1]');
      $this->form_validation->set_rules('parent','所屬Menu','trim|required|numeric|max_length[5]');
      $this->form_validation->set_rules('main_image','圖片','trim');
      //多語言判斷
      foreach($this->data['languages']->result_array() as $lg){
        $title='descriptions['.$lg["id"].'][title]'; 
        $content='descriptions['.$lg["id"].'][content]';
        $this->form_validation->set_rules($title,$lg['name'].' 標題','trim|required|max_length[100]');
        $this->form_validation->set_rules($content,$lg['name'].' 內容','trim');
      }
  }
  //執行刪除功能
  public function delete($delete_id=0){
    if(!empty($delete_id)){
      $result=$this->pages_mdl->delete_pages($delete_id);
      $this->operator_log('刪除基本頁面->ID:'.$delete_id,'刪除',$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      $redirect=site_url('admins/pages').$this->settings['url_query'];//獲取列表篩選參數
      redirect($redirect);
      
    }else{
      show_error('對不起,參數出錯!');
      exit;
    }
  }
 //重置檢視數
 public function reset($reset_id=''){
    if(!empty($reset_id)){
      $data['general']=array('view_num'=>0);
      $result=$this->pages_mdl->edit_pages($data,$reset_id);
      $this->operator_log('重置基本頁面檢視數->ID:'.$reset_id,'重置',$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      $redirect=site_url('admins/pages').$this->settings['url_query'];//獲取列表篩選參數
      redirect($redirect);
      
    }else{
      show_error('對不起,參數出錯!');
      exit;
    }
 }

  //--Banner廣告--//
  //相簿功能
  public function album($album_id=0){
    if(!empty($album_id)){
      $this->data['album_id']=$album_id;

      $album_title=$this->input->get('title');
      $album_title=!empty($album_title)?$album_title:$this->input->cookie('album_title');
      $cookie = array(
          'name'   => 'album_title',
          'value'  => $album_title,
          'expire' => '0',
          'path'   => '/',
      );
      $this->input->set_cookie($cookie);
      $this->data['title']=$album_title;

      $page = $this->input->get('p',TRUE);
      $page = (!empty($page) && is_numeric($page)) ? intval($page) : 1;
      $limit = $this->settings['default_admin_limit'];
      $offset = ($page - 1) * $limit;
      if($offset < 0){
        redirect('admins/pages/album/'.$album_id);
      }
      $url_query=$_SERVER['QUERY_STRING'];
      if(!empty($url_query)){
        $url_query=preg_replace('/&p=(\d+)/','',$url_query);
      }
      $data=array('album_id'=>$album_id,'limits'=>$limit,'offset'=>$offset);

      $this->data['lists_count']=$this->pages_mdl->totle_images($data);
      $pagination = '';
      if($this->data['lists_count'] > $limit)
      {
        $this->dpagination->currentPage($page);
        $this->dpagination->items($this->data['lists_count']);
        $this->dpagination->limit($limit);
        $this->dpagination->adjacents(5);
        $this->dpagination->target(site_url('admins/pages/album/'.$album_id).'?'.$url_query);
        $this->dpagination->parameterName('p');
        $this->dpagination->nextLabel($this->data['lang']['orders_lable_19']);
      $this->dpagination->PrevLabel($this->data['lang']['orders_lable_18']);
        $pagination = $this->dpagination->getOutput();
      }
      $this->data['pagination'] = $pagination;

      $this->data['images']=$this->pages_mdl->get_images($data);
      $this->load->view('admins/pages_images_view',$this->data);
    }else{
      show_error('對不起,參數出錯!');
      exit;
    }
  }

   //相簿圖片刪除
   public function album_delete($image_id='',$album_id='',$images=''){
     if(!empty($image_id) && !empty($album_id)){
        $images=$this->input->get('images');
        if(!empty($images) && file_exists($images)){
           Imagelib::delete_image($images); //刪除舊圖片.
           Imagelib::delete_thumb_image($images); //刪除舊圖片縮略圖.
         }
         $result=$this->pages_mdl->delete_image($image_id);
         $this->operator_log('刪除關於我們相簿圖片->ID:'.$image_id,'刪除',$result);
         $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
         $notify = $result > 0?'success':'error';
         $this->nsession->set_flashdata($notify, $msg);
         redirect("admins/pages/album/".$album_id);
     }
   }

  //執行上傳相簿圖片
  public function album_modify(){
     $modify_method=$this->input->post('modify_method'); //執行方法.
     $this->_load_validation_album($modify_method);
     $album_id=$this->input->post('album_id');
     if($this->form_validation->run() == FALSE){
         $this->data['error']=true;
         $this->album($album_id);
      }else{
         $old_images=$this->input->post('old_images');
         $images=$this->_upload_images('images',$old_images); //主圖片的上傳或修改.
         $data=array(
            'images'=>$images,
            'sort_order'=>$this->input->post('sort_order'),
            'description'=>$this->input->post('description'),
            'category_id'=>$album_id
          );
          $images_id=$this->input->post('images_id');
          if($images_id>0){
             $operator_title='修改消息相簿圖片->'.$images;
             $action='修改';
             $result=$this->pages_mdl->edit_images($data,$images_id);
          }else{
             $operator_title='新增消息相簿圖片->'.$images;
             $action='新增';
             $result=$this->pages_mdl->add_images($data);
          }
         $this->operator_log($operator_title,$action,$result);
         $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
         $notify = $result > 0?'success':'error';
         $this->nsession->set_flashdata($notify, $msg);
         redirect("admins/pages/album/".$album_id);
      }
  }

   //批量上傳圖片
  public function album_batch(){
      $album_id=$this->input->post('album_id');
      if(!empty($album_id)){
        $images=$this->input->post('images');
        $description=$this->input->post('description');
        $sort_order=$this->input->post('sort_order');
        $result=0;
        for ($i=0; $i < count($images); $i++) {
          $data=array(
            'images'=>$images[$i],
            'sort_order'=>$sort_order[$i],
            'description'=>$description[$i],
            'category_id'=>$album_id
          );
          $result+=$this->pages_mdl->add_images($data);
        }
        $this->operator_log('批量上傳關於我們相簿圖片->ID:'.$album_id,'批量上傳',$result);
        $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
        $notify = $result > 0?'success':'error';
        $this->nsession->set_flashdata($notify, $msg);
        redirect("admins/pages/album/".$album_id);
      }
   }

  //驗證相簿上傳的數據格式
  private function _load_validation_album($modify_method='add'){
     if($modify_method=='add'){
          $this->form_validation->set_rules('album_id','相簿ID','required|trim|numeric');
          $this->form_validation->set_rules('images','圖片','callback__images_check');
          $this->form_validation->set_rules('sort_order','排序','required|trim|numeric');
          $this->form_validation->set_rules('description','排序','trim');

     }else{
           $this->form_validation->set_rules('album_id','相簿ID','required|trim|numeric');
           $this->form_validation->set_rules('images_id','相片ID','required|trim|numeric');
           $this->form_validation->set_rules('old_images','舊相片','required|trim');
           $this->form_validation->set_rules('sort_order','排序','required|trim|numeric');
           $this->form_validation->set_rules('description','排序','trim');
     }
  }
  //驗證圖片
  function _images_check($str){
      $allowed_types=array('jpg','png','gif','jpeg');
      $temp_file=$_FILES['images']['tmp_name'];
      $f_name=$_FILES['images']['name'];
      $x = explode('.', $f_name);
      $f_extention=strtolower(end($x));
      if(!empty($temp_file) && $f_name && in_array($f_extention,$allowed_types)){
        return TRUE;
      }else{
        $this->form_validation->set_message('_images_check', '圖片不能為空,或格式不正確!');
         return FALSE;
      }
   }
}